// pages/game/game.js
const app = getApp();

Page({
  data: {
    level: 1,
    score: 0,
    targetScore: 1000,
    moves: 20,
    maxMoves: 20,
    timeLeft: 300, // 5分钟
    maxTime: 300,
    gameStatus: 'playing', // playing, paused, completed, failed
    board: [],
    boardSize: 8,
    selectedBlock: null,
    colors: ['#E74C3C', '#3498DB', '#F1C40F', '#2ECC71', '#9B59B6', '#E67E22'],
    animations: [],
    comboCount: 0,
    isProcessing: false,
    // 道具系统
    powerUps: {
      bomb: { count: 3, icon: '💣', name: '炸弹' },
      rainbow: { count: 2, icon: '🌈', name: '彩虹球' },
      rowClear: { count: 2, icon: '➡️', name: '行清除' },
      colClear: { count: 2, icon: '⬇️', name: '列清除' },
      shuffle: { count: 1, icon: '🔀', name: '打乱' }
    },
    selectedPowerUp: null, // 当前选中的道具
    powerUpMode: false // 是否在道具使用模式
  },

  onLoad(options) {
    const level = parseInt(options.level) || 1;
    this.setData({
      level: level,
      targetScore: 1000 + (level - 1) * 200,
      moves: 20 + Math.floor(level / 3) * 5,
      maxMoves: 20 + Math.floor(level / 3) * 5,
      timeLeft: 300 - (level - 1) * 10,
      maxTime: 300 - (level - 1) * 10
    });
    
    this.loadPowerUps();
    this.initGame();
    this.startTimer();
  },

  onUnload() {
    if (this.timer) {
      clearInterval(this.timer);
    }
    this.savePowerUps();
  },

  initGame() {
    this.generateBoard();
    this.removeInitialMatches();
  },

  generateBoard() {
    const board = [];
    for (let row = 0; row < this.data.boardSize; row++) {
      board[row] = [];
      for (let col = 0; col < this.data.boardSize; col++) {
        const color = this.getRandomColor();
        board[row][col] = {
          color: color,
          icon: this.getColorIcon(color),
          id: `${row}-${col}`,
          row: row,
          col: col,
          isSelected: false,
          isMatched: false
        };
      }
    }
    this.setData({ board });
  },

  getRandomColor() {
    const colors = this.data.colors;
    return colors[Math.floor(Math.random() * colors.length)];
  },

  getColorIcon(color) {
    const colorIconMap = {
      '#E74C3C': '♥',  // 红心 - 红色
      '#3498DB': '♦',  // 钻石 - 蓝色 
      '#F1C40F': '★',  // 星星 - 黄色
      '#2ECC71': '♣',  // 梅花 - 绿色
      '#9B59B6': '♠',  // 黑桃 - 紫色
      '#E67E22': '●'   // 圆点 - 橙色
    };
    return colorIconMap[color] || '●';
  },

  removeInitialMatches() {
    // 移除初始生成时的三连消除
    let hasMatches = true;
    while (hasMatches) {
      hasMatches = false;
      for (let row = 0; row < this.data.boardSize; row++) {
        for (let col = 0; col < this.data.boardSize; col++) {
          if (this.checkMatches(row, col).length > 0) {
            const newColor = this.getRandomColor();
            this.data.board[row][col].color = newColor;
            this.data.board[row][col].icon = this.getColorIcon(newColor);
            hasMatches = true;
          }
        }
      }
    }
    this.setData({ board: this.data.board });
  },

  onBlockTap(e) {
    if (this.data.isProcessing || this.data.gameStatus !== 'playing') return;
    
    const { row, col } = e.currentTarget.dataset;
    const rowNum = parseInt(row);
    const colNum = parseInt(col);
    
    // 如果在道具使用模式
    if (this.data.powerUpMode && this.data.selectedPowerUp) {
      this.usePowerUp(this.data.selectedPowerUp, rowNum, colNum);
      return;
    }
    
    if (this.data.selectedBlock) {
      if (this.data.selectedBlock.row === rowNum && this.data.selectedBlock.col === colNum) {
        // 取消选择
        this.clearSelection();
      } else if (this.isAdjacent(this.data.selectedBlock, { row: rowNum, col: colNum })) {
        // 交换方块
        this.swapBlocks(this.data.selectedBlock, { row: rowNum, col: colNum });
      } else {
        // 选择新方块
        this.selectBlock(rowNum, colNum);
      }
    } else {
      // 选择方块
      this.selectBlock(rowNum, colNum);
    }
  },

  selectBlock(row, col) {
    this.clearSelection();
    this.data.board[row][col].isSelected = true;
    this.setData({
      board: this.data.board,
      selectedBlock: { row, col }
    });
  },

  clearSelection() {
    if (this.data.selectedBlock) {
      const { row, col } = this.data.selectedBlock;
      this.data.board[row][col].isSelected = false;
    }
    this.setData({
      board: this.data.board,
      selectedBlock: null
    });
  },

  isAdjacent(block1, block2) {
    const rowDiff = Math.abs(block1.row - block2.row);
    const colDiff = Math.abs(block1.col - block2.col);
    return (rowDiff === 1 && colDiff === 0) || (rowDiff === 0 && colDiff === 1);
  },

  swapBlocks(block1, block2) {
    this.setData({ isProcessing: true });
    
    const board = this.data.board;
    const tempColor = board[block1.row][block1.col].color;
    const tempIcon = board[block1.row][block1.col].icon;
    
    board[block1.row][block1.col].color = board[block2.row][block2.col].color;
    board[block1.row][block1.col].icon = board[block2.row][block2.col].icon;
    board[block2.row][block2.col].color = tempColor;
    board[block2.row][block2.col].icon = tempIcon;
    
    // 检查是否有匹配
    const matches1 = this.checkMatches(block1.row, block1.col);
    const matches2 = this.checkMatches(block2.row, block2.col);
    
    if (matches1.length > 0 || matches2.length > 0) {
      // 有匹配，处理消除
      this.clearSelection();
      this.setData({ 
        board: board,
        moves: this.data.moves - 1 
      });
      
      setTimeout(() => {
        this.processMatches();
      }, 300);
    } else {
      // 无匹配，交换回来
      const tempColor2 = board[block1.row][block1.col].color;
      const tempIcon2 = board[block1.row][block1.col].icon;
      
      board[block1.row][block1.col].color = board[block2.row][block2.col].color;
      board[block1.row][block1.col].icon = board[block2.row][block2.col].icon;
      board[block2.row][block2.col].color = tempColor2;
      board[block2.row][block2.col].icon = tempIcon2;
      
      this.setData({ 
        board: board,
        isProcessing: false 
      });
      
      wx.showToast({
        title: '无效移动',
        icon: 'none',
        duration: 1000
      });
    }
  },

  checkMatches(row, col) {
    const board = this.data.board;
    const color = board[row][col].color;
    const matches = [];
    
    // 检查水平匹配
    let horizontalMatches = [{ row, col }];
    
    // 向左检查
    for (let i = col - 1; i >= 0; i--) {
      if (board[row][i].color === color) {
        horizontalMatches.unshift({ row, col: i });
      } else {
        break;
      }
    }
    
    // 向右检查
    for (let i = col + 1; i < this.data.boardSize; i++) {
      if (board[row][i].color === color) {
        horizontalMatches.push({ row, col: i });
      } else {
        break;
      }
    }
    
    if (horizontalMatches.length >= 3) {
      matches.push(...horizontalMatches);
    }
    
    // 检查垂直匹配
    let verticalMatches = [{ row, col }];
    
    // 向上检查
    for (let i = row - 1; i >= 0; i--) {
      if (board[i][col].color === color) {
        verticalMatches.unshift({ row: i, col });
      } else {
        break;
      }
    }
    
    // 向下检查
    for (let i = row + 1; i < this.data.boardSize; i++) {
      if (board[i][col].color === color) {
        verticalMatches.push({ row: i, col });
      } else {
        break;
      }
    }
    
    if (verticalMatches.length >= 3) {
      matches.push(...verticalMatches);
    }
    
    // 去重
    const uniqueMatches = [];
    matches.forEach(match => {
      if (!uniqueMatches.find(m => m.row === match.row && m.col === match.col)) {
        uniqueMatches.push(match);
      }
    });
    
    return uniqueMatches;
  },

  processMatches() {
    let allMatches = [];
    
    // 找到所有匹配
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        const matches = this.checkMatches(row, col);
        matches.forEach(match => {
          if (!allMatches.find(m => m.row === match.row && m.col === match.col)) {
            allMatches.push(match);
          }
        });
      }
    }
    
    if (allMatches.length > 0) {
      // 计算分数
      const baseScore = allMatches.length * 10;
      const comboBonus = this.data.comboCount * 5;
      const totalScore = baseScore + comboBonus;
      
      // 标记匹配的方块
      allMatches.forEach(match => {
        this.data.board[match.row][match.col].isMatched = true;
      });
      
      this.setData({
        board: this.data.board,
        score: this.data.score + totalScore,
        comboCount: this.data.comboCount + 1
      });
      
      // 播放消除动画
      setTimeout(() => {
        this.removeMatches();
      }, 500);
    } else {
      // 没有匹配，重置连击
      this.setData({
        comboCount: 0,
        isProcessing: false
      });
      
      this.checkGameStatus();
    }
  },

  removeMatches() {
    // 移除匹配的方块
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        if (this.data.board[row][col].isMatched) {
          this.data.board[row][col].color = '';
          this.data.board[row][col].isMatched = false;
        }
      }
    }
    
    this.setData({ board: this.data.board });
    
    // 方块下落
    setTimeout(() => {
      this.dropBlocks();
    }, 300);
  },

  dropBlocks() {
    let board = this.data.board;
    let hasDropped = false;
    
    // 让方块下落
    for (let col = 0; col < this.data.boardSize; col++) {
      for (let row = this.data.boardSize - 1; row >= 0; row--) {
        if (board[row][col].color === '') {
          // 找到上面第一个非空方块
          for (let newRow = row - 1; newRow >= 0; newRow--) {
            if (board[newRow][col].color !== '') {
              board[row][col].color = board[newRow][col].color;
              board[newRow][col].color = '';
              hasDropped = true;
              break;
            }
          }
        }
      }
    }
    
    // 填充新方块
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        if (board[row][col].color === '') {
          const newColor = this.getRandomColor();
          board[row][col].color = newColor;
          board[row][col].icon = this.getColorIcon(newColor);
          hasDropped = true;
        }
      }
    }
    
    this.setData({ board: board });
    
    if (hasDropped) {
      // 继续检查匹配
      setTimeout(() => {
        this.processMatches();
      }, 500);
    } else {
      this.setData({ isProcessing: false });
      this.checkGameStatus();
    }
  },

  startTimer() {
    this.timer = setInterval(() => {
      if (this.data.gameStatus === 'playing') {
        const timeLeft = this.data.timeLeft - 1;
        this.setData({ timeLeft });
        
        if (timeLeft <= 0) {
          this.gameOver(false);
        }
      }
    }, 1000);
  },

  checkGameStatus() {
    if (this.data.score >= this.data.targetScore) {
      this.gameOver(true);
    } else if (this.data.moves <= 0) {
      this.gameOver(false);
    }
  },

  gameOver(isWin) {
    if (this.timer) {
      clearInterval(this.timer);
    }
    
    this.setData({
      gameStatus: isWin ? 'completed' : 'failed'
    });
    
    if (isWin) {
      // 更新最佳分数和解锁关卡
      const isNewRecord = app.updateBestScore(this.data.level, this.data.score);
      if (this.data.level >= app.globalData.currentLevel) {
        app.globalData.currentLevel = this.data.level + 1;
        app.saveGameData();
      }
      
      // 随机奖励道具
      if (Math.random() < 0.3) { // 30%几率获得道具
        this.awardRandomPowerUp();
      }
      
      wx.navigateTo({
        url: `/pages/result/result?win=true&score=${this.data.score}&level=${this.data.level}&newRecord=${isNewRecord}`
      });
    } else {
      wx.navigateTo({
        url: `/pages/result/result?win=false&score=${this.data.score}&level=${this.data.level}`
      });
    }
  },

  pauseGame() {
    this.setData({
      gameStatus: this.data.gameStatus === 'paused' ? 'playing' : 'paused'
    });
  },

  restartGame() {
    wx.showModal({
      title: '重新开始',
      content: '确定要重新开始这个关卡吗？',
      success: (res) => {
        if (res.confirm) {
          this.setData({
            score: 0,
            moves: this.data.maxMoves,
            timeLeft: this.data.maxTime,
            gameStatus: 'playing',
            comboCount: 0,
            selectedBlock: null,
            isProcessing: false,
            powerUpMode: false,
            selectedPowerUp: null
          });
          this.initGame();
        }
      }
    });
  },

  goBack() {
    wx.showModal({
      title: '退出游戏',
      content: '确定要退出当前游戏吗？',
      success: (res) => {
        if (res.confirm) {
          wx.navigateBack();
        }
      }
    });
  },

  // 道具系统方法
  onPowerUpTap(e) {
    const { type } = e.currentTarget.dataset;
    if (this.data.powerUps[type].count <= 0) {
      wx.showToast({
        title: '道具数量不足',
        icon: 'none'
      });
      return;
    }
    
    if (this.data.powerUpMode && this.data.selectedPowerUp === type) {
      // 取消道具选择
      this.setData({
        powerUpMode: false,
        selectedPowerUp: null
      });
    } else {
      // 选中道具
      this.setData({
        powerUpMode: true,
        selectedPowerUp: type
      });
      
      // 如果是打乱道具，直接使用
      if (type === 'shuffle') {
        this.usePowerUp(type);
      } else {
        wx.showToast({
          title: '请点击目标位置',
          icon: 'none'
        });
      }
    }
  },

  usePowerUp(type, row, col) {
    if (this.data.powerUps[type].count <= 0) return;
    
    this.setData({ isProcessing: true });
    
    switch (type) {
      case 'bomb':
        this.useBombPowerUp(row, col);
        break;
      case 'rainbow':
        this.useRainbowPowerUp(row, col);
        break;
      case 'rowClear':
        this.useRowClearPowerUp(row);
        break;
      case 'colClear':
        this.useColClearPowerUp(col);
        break;
      case 'shuffle':
        this.useShufflePowerUp();
        break;
    }
    
    // 消耗道具
    const powerUps = this.data.powerUps;
    powerUps[type].count--;
    
    this.setData({
      powerUps: powerUps,
      powerUpMode: false,
      selectedPowerUp: null
    });
  },

  useBombPowerUp(centerRow, centerCol) {
    const board = this.data.board;
    const toRemove = [];
    
    // 获取炸弹范围内的方块 (3x3区域)
    for (let row = Math.max(0, centerRow - 1); row <= Math.min(this.data.boardSize - 1, centerRow + 1); row++) {
      for (let col = Math.max(0, centerCol - 1); col <= Math.min(this.data.boardSize - 1, centerCol + 1); col++) {
        toRemove.push({ row, col });
      }
    }
    
    // 标记要清除的方块
    toRemove.forEach(pos => {
      board[pos.row][pos.col].isMatched = true;
    });
    
    // 计算分数
    const score = toRemove.length * 15; // 炸弹清除分数更高
    
    this.setData({
      board: board,
      score: this.data.score + score
    });
    
    wx.showToast({
      title: `炸弹清除 +${score}分`,
      icon: 'none'
    });
    
    // 播放清除动画
    setTimeout(() => {
      this.removeMatches();
    }, 500);
  },

  useRainbowPowerUp(row, col) {
    const board = this.data.board;
    const targetColor = board[row][col].color;
    const toRemove = [];
    
    // 找到所有相同颜色的方块
    for (let r = 0; r < this.data.boardSize; r++) {
      for (let c = 0; c < this.data.boardSize; c++) {
        if (board[r][c].color === targetColor) {
          toRemove.push({ row: r, col: c });
        }
      }
    }
    
    // 标记要清除的方块
    toRemove.forEach(pos => {
      board[pos.row][pos.col].isMatched = true;
    });
    
    // 计算分数
    const score = toRemove.length * 20; // 彩虹球清除分数更高
    
    this.setData({
      board: board,
      score: this.data.score + score
    });
    
    wx.showToast({
      title: `彩虹球清除 +${score}分`,
      icon: 'none'
    });
    
    // 播放清除动画
    setTimeout(() => {
      this.removeMatches();
    }, 500);
  },

  useRowClearPowerUp(row) {
    const board = this.data.board;
    const toRemove = [];
    
    // 清除整行
    for (let col = 0; col < this.data.boardSize; col++) {
      toRemove.push({ row, col });
    }
    
    // 标记要清除的方块
    toRemove.forEach(pos => {
      board[pos.row][pos.col].isMatched = true;
    });
    
    // 计算分数
    const score = toRemove.length * 12;
    
    this.setData({
      board: board,
      score: this.data.score + score
    });
    
    wx.showToast({
      title: `行清除 +${score}分`,
      icon: 'none'
    });
    
    // 播放清除动画
    setTimeout(() => {
      this.removeMatches();
    }, 500);
  },

  useColClearPowerUp(col) {
    const board = this.data.board;
    const toRemove = [];
    
    // 清除整列
    for (let row = 0; row < this.data.boardSize; row++) {
      toRemove.push({ row, col });
    }
    
    // 标记要清除的方块
    toRemove.forEach(pos => {
      board[pos.row][pos.col].isMatched = true;
    });
    
    // 计算分数
    const score = toRemove.length * 12;
    
    this.setData({
      board: board,
      score: this.data.score + score
    });
    
    wx.showToast({
      title: `列清除 +${score}分`,
      icon: 'none'
    });
    
    // 播放清除动画
    setTimeout(() => {
      this.removeMatches();
    }, 500);
  },

  useShufflePowerUp() {
    const board = this.data.board;
    const colors = [];
    
    // 收集所有方块的颜色
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        colors.push(board[row][col].color);
      }
    }
    
    // 打乱颜色数组
    for (let i = colors.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [colors[i], colors[j]] = [colors[j], colors[i]];
    }
    
    // 重新分配颜色
    let colorIndex = 0;
    for (let row = 0; row < this.data.boardSize; row++) {
      for (let col = 0; col < this.data.boardSize; col++) {
        const newColor = colors[colorIndex++];
        board[row][col].color = newColor;
        board[row][col].icon = this.getColorIcon(newColor);
      }
    }
    
    this.setData({ board: board });
    
    wx.showToast({
      title: '棋盘已打乱',
      icon: 'success'
    });
    
    // 重置状态
    setTimeout(() => {
      this.setData({ isProcessing: false });
    }, 1000);
  },

  // 道具管理方法
  loadPowerUps() {
    const app = getApp();
    try {
      const storedPowerUps = wx.getStorageSync('powerUps');
      if (storedPowerUps) {
        this.setData({ powerUps: storedPowerUps });
      }
    } catch (e) {
      console.log('加载道具数据失败:', e);
    }
  },

  savePowerUps() {
    try {
      wx.setStorageSync('powerUps', this.data.powerUps);
    } catch (e) {
      console.log('保存道具数据失败:', e);
    }
  },

  awardRandomPowerUp() {
    const powerUpTypes = ['bomb', 'rainbow', 'rowClear', 'colClear'];
    const randomType = powerUpTypes[Math.floor(Math.random() * powerUpTypes.length)];
    
    const powerUps = this.data.powerUps;
    powerUps[randomType].count++;
    
    this.setData({ powerUps: powerUps });
    this.savePowerUps();
    
    wx.showToast({
      title: `获得${powerUps[randomType].name}道具!`,
      icon: 'success'
    });
  }
})